package cn.wen.yinxiu.member.server.socket.handler;

import cn.wen.yinxiu.common.toolkit.SocketChannelUtil;
import cn.wen.yinxiu.member.builder.BeanBuilderAssistant;
import cn.wen.yinxiu.member.server.protocol.Command;
import cn.wen.yinxiu.member.server.protocol.msg.MsgGroupRequest;
import cn.wen.yinxiu.member.server.protocol.msg.MsgGroupResponse;
import cn.wen.yinxiu.member.service.UsersService;
import cn.wen.yinxiu.member.vo.UserInfo;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Date;

/**
 * @ClassName: MsgGroupHandler
 * @Author: 小飞
 * @Date: 2023/5/28 14:34
 * @Description: 群组群发消息
 */
@Slf4j
public class MsgGroupHandler extends SimpleChannelInboundHandler<MsgGroupRequest> {

    private final UsersService userService;

    public MsgGroupHandler(UsersService userService) {
        this.userService = userService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MsgGroupRequest msg) throws Exception {
        msg.setMsgTime(new Date());
        // 获取群组通信管道
        ChannelGroup channelGroup = SocketChannelUtil.getChannelGroup(msg.getTalkId());
        Channel channel = ctx.channel();
        if (null == channelGroup) {
            SocketChannelUtil.addChannelGroup(msg.getTalkId(), channel);
            channelGroup = SocketChannelUtil.getChannelGroup(msg.getTalkId());
        }
        // 异步写库
        userService.asyncAppendChatRecord(BeanBuilderAssistant.buildUserInfo(msg));
        // 群发消息
        UserInfo userInfo = userService.queryUserInfo(msg.getUserId());
        MsgGroupResponse msgGroupResponse = BeanBuilderAssistant.buildMsgResponse(userInfo, msg);
        // 发送数据
        channelGroup.writeAndFlush(new TextWebSocketFrame(getByteBuf(ctx, msg.getUserId(), msgGroupResponse)));
    }

    public ByteBuf getByteBuf(ChannelHandlerContext ctx, Long userId, MsgGroupResponse msgGroupResponse) {
        ByteBuf bytebuf = ctx.alloc().buffer();
        JSONObject data = new JSONObject();
        data.put("type", Command.MsgGroupResponse);
        data.put("code", 200);
        JSONObject params = new JSONObject();
        params.put("userId", userId);
        params.put("msgGroupInfo", msgGroupResponse);
        data.put("data", params);
        log.info("登录成功后的返回数据：{}", data);
        byte []bytes = data.toJSONString().getBytes(Charset.forName("utf-8"));
        bytebuf.writeBytes(bytes);
        return bytebuf;
    }
}
